package com.teradata.controller;

import com.teradata.entities.Result;
import com.teradata.entities.User;
import com.teradata.enums.ResultEnum;
import com.teradata.service.UserService;
import com.teradata.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @RestController = @Configuration + @ResponseBody
 */
@RestController
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @GetMapping("/hello")
    //@ResponseBody
    public Map<String, String> hello() {
        HashMap<String, String> hello = new HashMap<>();
        hello.put("data", "hello 小红");
        hello.put("status", "SUCCESS");
        return hello;
    }

    @GetMapping("/userlist")
    public List<User> getUserList() {
        return userService.getUserList();
    }

    @GetMapping("/userlist2map")
    public List<Map<String, Object>> getUserListMap() {
        return userService.getUserListToMapDef();
    }

    @GetMapping("/userall")
    public List<User> getAll() {
        return userService.getUsers();
    }

    @GetMapping("/all")
    public List<User> selectAll() {
        return userService.selectAll();
    }

    @GetMapping("/user/{id}")
    public Result getUser(@PathVariable int id) {
        if (id < 0) {
            return ResultUtil.error(ResultEnum.PARAM_ERROR);
        }
        return ResultUtil.success(userService.getUserById(id));
    }

    @GetMapping("/user/cp/{id}/{name}")
    public List<User> cpUser(@PathVariable int id, @PathVariable String name) {
        userService.copyUser(id, name);
        return userService.getUserList();
    }

    @GetMapping("/userlistmap")
    public List<Map<String, Object>> getAllListMap() {
        return userService.getUserListMap();
    }


    @PostMapping("/user/save")
    public Result saveUser(@Validated(User.UPDATE.class) User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            logger.info("验证失败: {}", bindingResult.getFieldError().getDefaultMessage());
            return ResultUtil.error(ResultEnum.PARAM_ERROR, bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(userService.saveUser(user));
    }
}
